<template>
	<view class="page_wrap">
		<custom-header :back="false" title="登录" />
		<view class="bg"></view>
		<view class="login_wrap">
			<view class="logo">
				<image src="/static/login/logo.png" mode=""></image>
			</view>
			<view class="text_logo">
				<image src="/static/login/text_logo.png" mode=""></image>
			</view>
			<view class="form_wrap">
				<view class="form_item phone">
					<view class="icon">
						<image src="/static/login/phone_icon.png" mode=""></image>
					</view>
					<view class="input">
						<input type="number" v-model="phone" placeholder="请输入手机号码" />
					</view>
					<view class="right"></view>
				</view>
				<view class="form_item code">
					<view class="icon">
						<image src="/static/login/code_icon.png" mode=""></image>
					</view>
					<view class="input">
						<input type="number" v-model="code" placeholder="请输入验证码" />
					</view>
					<view
						class="right"
						hover-class="custom_hover"
						:hover-stay-time="200"
						@click="getVerificationCode">
							{{ buttonText }}
					</view>
				</view>
				<view class="btn_wrap">
					<button
						size="default" 
						type="default" 
						class="btn"
						hover-class="confirm_hover"
						:hover-stay-time="200"
						@click="handleLogin">立即登录</button>
				</view>
				<view class="register">
					<view 
						class="btn"
						hover-class="custom_hover"
						:hover-stay-time="200"
						@click="handleRegister">卖家入驻申请</view>
				</view>
			</view>
		</view>
		<view class="read"  @click="checked = !checked">
			<view class="icon">
				<image src="/static/common/check.png" mode="" v-if="checked"></image>
				<image src="/static/common/no_check.png" mode="" v-else></image>
			</view>
			<view class="text">
				登录即代表您同意
				<text @click.stop="handleShowNotice">《用户协议》</text>
				和
				<text @click.stop="handleShowNotice">《隐私政策》</text>
			</view>
		</view>
	</view>
	<!-- 自定义消息弹出层 -->
	<custom-popup
		:show="isShowToast" 
		:config="popupConfig"
		@confirm="isShowToast = false">
	</custom-popup>
</template>

<script setup>
	import { ref,computed,onUnmounted } from 'vue'
	import { onLoad } from "@dcloudio/uni-app";
	import { useStore } from 'vuex'
	import { isvalidPhoneNumber } from '../../utils/validate.js'
	import authApi from '@/api/auth'
	import { setToken, setUserInfo } from '@/utils/request'


	const store = useStore()
	
	const statusBarHeight = computed(()=>{
		return store.getters.statusBarHeight
	}) 
	
	// 弹窗提示
	const isShowToast = ref(false)
	const popupConfig  = ref({})
	
	const phone = ref('')
	const code = ref('')
	const isCounting = ref(false)
	const countdown = ref(0)
	const totalTime = ref(60)
	const copySuccess = ref(false)
	
	// 计算按钮文本
	const buttonText = computed(() => {
	  if (isCounting.value) {
		return `(${countdown.value}S)重新获取`
	  }
	  return countdown.value === 0 ? '重新获取' : '获取验证码'
	})
	
	// 获取验证码
	const getVerificationCode = async () => {

	  if (isCounting.value) return

	  if (!phone.value) {
			popupConfig.value.message = '请输入手机号码'
			isShowToast.value = true
			return
	  }

	  if (!isvalidPhoneNumber(phone.value)) {
	  		popupConfig.value.message = '手机号码格式不正确'
	  		isShowToast.value = true
	  		return
	  }

	  try {
		// 显示加载状态
		uni.showLoading({
			title: '发送中...'
		})

		console.log(`开始获取验证码，手机号: ${phone.value}`)
		const result = await authApi.getLoginCode(phone.value)
		// 显示成功提示
		uni.showToast({
			title: '验证码发送成功',
			icon: 'success'
		})

		// 开始倒计时
		startCountdown()

	  } catch (error) {
		console.error('获取验证码失败:', error)

		// 显示错误提示
		popupConfig.value.message = error.message || '验证码发送失败，请重试'
		isShowToast.value = true

	  } finally {
		// 隐藏加载状态
		uni.hideLoading()
	  }
	}
	
	// 开始倒计时
	const startCountdown = () => {
	  isCounting.value = true
	  countdown.value = totalTime.value
	  
	  // 设置定时器
	  const timer = setInterval(() => {
		countdown.value--
		
		if (countdown.value <= 0) {
		  clearInterval(timer)
		  isCounting.value = false
		}
	  }, 1000)
	  
	  // 存储定时器以便清理
	  timerRef.value = timer
	}
	
	// 存储定时器引用
	const timerRef = ref(null)
	
	// 组件卸载时清除定时器
	onUnmounted(() => {
	  if (timerRef.value) {
		clearInterval(timerRef.value)
	  }
	})
	
	
	// 同意阅读
	const checked = ref(false)
	const handleShowNotice = ()=>{}

	// 登录
	const handleLogin = async () => {
		// 验证手机号
		if (!phone.value) {
			popupConfig.value.message = '请输入手机号码'
			isShowToast.value = true
			return
		}

		if (!isvalidPhoneNumber(phone.value)) {
			popupConfig.value.message = '手机号码格式不正确'
			isShowToast.value = true
			return
		}

		// 验证验证码
		if (!code.value) {
			popupConfig.value.message = '请输入验证码'
			isShowToast.value = true
			return
		}

		try {
			// 显示加载状态
			uni.showLoading({
				title: '登录中...'
			})

			// 调用登录API 
			// const result = await authApi.phoneCodeLogin({
			// 	phone: phone.value,
			// 	code: code.value
			// })

			// TODO 用测试接口，后续记得删掉改用上面的
			const result = await authApi.getTestToken("17601324399")
			if (result.authorization) {
				setToken(result.authorization)
			}
			if (result.userInfo) {
				setUserInfo(result.userInfo)
			}

			// 显示成功提示
			uni.showToast({
				title: '登录成功',
				icon: 'success'
			})

			// 延迟跳转到首页
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/my/my'
				})
			}, 1500)

		} catch (error) {
			console.error('登录失败:', error)

			// 显示错误提示
			popupConfig.value.message = error.message || '登录失败，请重试'
			isShowToast.value = true

		} finally {
			// 隐藏加载状态
			uni.hideLoading()
		}
	}
	
	// 注册
	const handleRegister = ()=>{
		uni.navigateTo({
			url:'/pages/register/register'
		})
	}
</script>

<style lang="scss">
	.page_wrap{
		min-height: 100vh;
		background: #fff;
	}
	.bg{
		width: 100%;
		height: 253rpx;
		background: url('https://goods-1312936761.cos.ap-chongqing.myqcloud.com/applet/supplier/login/bg.png');
		background-size: cover;
		position: relative;
		z-index: 1;
	}
	.login_wrap{
		transform: translateY(-150rpx);
	}
	.logo{
		width: 180rpx;
		height: 120rpx;
		margin: 0 auto;
	}
	.text_logo{
		width: 325rpx;
		height: 80rpx;
		margin:60rpx auto 0;
	}
	.form_wrap{
		padding:30rpx 75rpx 0;
		.form_item{
			height: 88rpx;
			border-radius: 99rpx;
			background: #F8F8F8;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 28rpx;
			padding:0 25rpx;
			margin-top: 40rpx;
			.icon{
				width: 28rpx;
				height: 28rpx;
				display: flex;
			}
			.input{
				flex: 1;
				padding-left: 20rpx;
				input{
					width: 100%;
				}
			}
			.right{
				width: 200rpx;
				color: #F5564D;
				text-align: center;
			}
		}
	}
	.btn_wrap{
		margin-top: 50rpx;
		.btn{
			// width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-radius: 99rpx;
			background: #F5564D;
			color: #fff;
			font-size: 32rpx;
			font-weight: bold;
		}
	}
	.register{
		padding-top: 30rpx;
		display: flex;
		justify-content: flex-end;
		color: #F5564D;
		font-size: 28rpx;
	}
	.read{
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		position: fixed;
		bottom: 120rpx;
		left: 0;
		.icon{
			width: 24rpx;
			height: 24rpx;
			display: flex;
		}
		.text{
			font-size: 24rpx;
			color: #bbb;
			padding-left: 10rpx;
			text{
				color: #F5564D;
			}
		}
	}
	
</style>
